import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI } from '@/apis/user'
import { useCartStore } from './cartStore'
import { mergeCartAPI } from '@/apis/cart'

export const useUserStore = defineStore(
  'user',
  () => {
    // 1. 定义管理用户数据的state
    const userInfo = ref({})
    const token = ref(null) // 存储token

    // 2. 定义获取接口数据的action函数
    const cartStore = useCartStore()

    const getUserInfo = async ({ account, password }) => {
      console.log(account, password)
      const res = await loginAPI({ account, password })
      console.log(res)

      // 假设服务器返回的数据结构是 { data: {...}, token: '...' }
      if (res.data.token) {
        token.value = res.data.token // 存储token
        localStorage.setItem('userToken', res.data.token) // 可选：持久化token到localStorage或cookie
      }

      userInfo.value = res.data
      console.log(userInfo.value)

      // 执行合并购物车的操作
      await mergeCartAPI(
        cartStore.cartList.map((item) => ({
          skuId: item.skuId,
          count: item.count,
          selected: item.selected
        }))
      )

      cartStore.updateCart()
    }

    // 退出时清除用户对象和token
    const clearUserInfo = () => {
      userInfo.value = {}
      token.value = null
      localStorage.removeItem('userToken') // 清除持久化的token
      cartStore.cartClear()
    }

    // 3. 以对象的格式把state和action return
    return {
      getUserInfo,
      userInfo,
      token, // 返回token以便其他地方可以访问它
      clearUserInfo
    }
  },
  {
    persist: true
  }
)
